package conf;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

public class XmlDo {
    protected Document document;//文档对象,内存中的dom树

    public XmlDo(String file,String charset) throws IOException {
        document = Jsoup.parse(new File(file), charset);
    }

    public XmlDo(String xml){
        document = Jsoup.parse(xml);
    }

    /*
    * 根据id属性值获取唯一的element对象
    */
    public Element getElementById(String id)
    {
        return document.getElementById(id);
    }

    /*
     * 根据标签名称获取元素对象集合
     */
    public Elements getElementsByTag(String tag)
    {
        return document.getElementsByTag(tag);
    }

    /*
     * 根据属性名称获取元素对象集合
     */
    public Elements getElementsByAttribute(String key)
    {
        return document.getElementsByAttribute(key);
    }

    /*
     * 根据对应的属性名和属性值获取元素对象集合
     */
    public Elements getElementsByAttributeValue(String key, String value)
    {
        return document.getElementsByAttributeValue(key,value);
    }

    public String getValueByElementAttribute(Element element,String key)
    {
        return element.attr(key);
    }

    public String getTextByElement(Element element)
    {
        return element.text();
    }

    public Element getElementByIndex(Elements elements,int idx)
    {
        if (idx<=0) {
            return elements.first();
        }
        else if (idx>=elements.size()) {
            return elements.last();
        }
        return elements.get(idx);
    }
}
